<template>
  <div>


    <div class="calculate setinput" >
      <li>试算：<el-input v-model="calculateExpression"></el-input>
        <el-button @click="calculate">试算</el-button></li>

      <li>结果：{{calcaulateValue}}</li>
    </div>
    <div class=" setinput"> 用户id：{{jufaanguserid}} <el-button @click="changeLoginflage(true)">设置</el-button>

      <el-dialog title="我是谁" :visible.sync="loginuserflag">

       <el-input v-model="tempjufanloginuser"></el-input>
        <div slot="footer" class="dialog-footer">
          <el-button @click="changeLoginflage(false)">取 消</el-button>
          <el-button type="primary" @click="login">确 定</el-button>
        </div>
      </el-dialog>



    </div>
    <div class=" setinput"> 标题：<el-input v-model="casetitle"></el-input>  </div>

    <div class=" setinput"> 规则id：<el-input v-model="ruleId"></el-input> <el-button @click="getRuleInfo">确定</el-button>
     </div>

    <div class="block">

      zip包： <el-cascader
        v-model="zipselectcascade"
        :options="zipdtoCascade"
        expand-trigger="hover"

        :props="{ expandTrigger:'hover',value:'id',label:'name' }"
        @change="getFilesContent">

      </el-cascader>
      <span><br> 类型： <selectTool :options="cwtype" label="name" @selectedindex="getzipZLBSXLindex"  style="display: inline-block"></selectTool></span>

    </div>




    <div style="display: inline-block ; width: 100%" >指标信息区：
      <ruleInfo :ruleinfo = "ruleinfo"></ruleInfo>


    </div>

    <hr>


    <div>

      <div>需要修改的key {{fileString}}

        <div style="border:1px  ">值：
          <el-button type="primary"  size="mini" @click="addNewTask(tasks)">新增</el-button>

          <el-table :data="tasks">

            <el-table-column label="iscwbw" width="50px">
              <template slot-scope="{row,index}">

                <el-checkbox v-model="row.iscwbw"  @change="setRowIscwbw($event,row)"></el-checkbox>
              </template>
            </el-table-column>

            <el-table-column label="xml"  width="500px">
              <template slot-scope="{row,index}">
                <span v-show="!row.editable" @dblclick="edit(row,index)">{{ zipfiles[row.xmlIndex]?zipfiles[row.xmlIndex].name:0 }}</span>



                <selectTool ref= 'clearselect' :options="zipfiles"  label="name" @selectedindex="setRowXmlIndex($event,row)"  v-show="row.editable" style="display: inline-block"></selectTool>

              </template>
            </el-table-column>

<el-table-column label="key">
              <template slot-scope="{row,index}">
                <span v-show="!row.editable" @dblclick="edit(row,index)">{{row.key }}</span>
                <el-input  v-show="row.editable" v-model="row.key"></el-input>
              </template>
            </el-table-column>



            <el-table-column
              type="index"
              width="50">

              <template slot-scope="{row,$index}">
                <span v-show="!row.editable">{{$index+1}}</span>
                <el-button v-show="row.editable" type="primary" icon="el-icon-check" size='mini'
                           @click=updatetask(row)></el-button>
                <el-button class="marginleftset" v-show="row.editable" type="primary" icon="el-icon-close" size='mini'
                           @click=deletetask($index,row)></el-button>

              </template>
            </el-table-column>
            <el-table-column label="value">
              <template slot-scope="{row,index}">
                <span v-show="!row.editable" @dblclick="edit(row,index)">{{row.value }}</span>
                <el-input  v-show="row.editable" v-model="row.value"></el-input>
                <!-- <span v-show="!row.editable" @dblclick="edit(row,index)">{{row.executor}}</span>
                 <el-input v-show="row.editable"  v-model="row.executor.toString()"  ></el-input>-->

              </template>
            </el-table-column>

            <el-table-column label="confirm">
              <template slot-scope="{row,index}">
                <!-- <span v-show="!row.editable" @dblclick="edit(row,index)">{{row.executor}}</span>
                 <el-input v-show="row.editable"  v-model="row.executor.toString()"  ></el-input>-->
                <el-button type="primary" size="mini" @click="edit(row,index)" v-show="!row.editable">修改</el-button>
                <el-button type="primary" size="mini" @click="updateValue(row,index)" v-show="row.editable">确定</el-button>
              </template>
            </el-table-column>



          </el-table>
        </div>

        <div><!--<el-button  @click="savexml"  icon="el-icon-download" type="primary">保存此xml</el-button>
          <el-button  @click="submitChange"  icon="el-icon-download" type="primary">提交修改</el-button>-->
          <el-button   v-loading="loading"
                       element-loading-text="拼命加载中"
                       element-loading-spinner="el-icon-loading"
                       element-loading-background="rgba(0, 0, 0, 0.8)"  @click="send"  icon="el-icon-download" type="primary"  :disabled="senddisabled">发送请求</el-button>
          <el-button @click="flushsenddisabled">刷新发送按钮</el-button>
          <el-button  @click="downLoadFile"  icon="el-icon-download" type="primary">下载zip包</el-button>
          <el-button  @click="resetall"  icon="el-icon-download" type="primary">重置所有</el-button></div>


      </div>


      <hr>



      <!--========================华丽的分割线==================-->

      <ol>
        <li>zip包名: <span>{{repContent.zipname}}</span></li>
        <li>xml修改记录: <span> {{repContent.filechange}}</span></li>
        <li>修改后zip路径：<span>{{zipfileurl.path}}</span></li>
        <li>返回值: <span></span></li>

      </ol>
      <div v-if="repContent.repContent  && repContent.repContent[0].errorMsg"> {{repContent.repContent[0].errorMsg}}</div>
      <div  v-else-if="repContent.repContent  && repContent.repContent[0]" >

        <ol>
          <li> 档案号：{{repContent.repContent[0].djxh}}</li>
          <li> 错误规则数量：{{repContent.repContent[0].ruleErrorCount}}</li>
          <li> 征期ID：{{repContent.repContent[0].zqId}}</li>
          <li> 检测规则数量：{{repContent.repContent[0].ruleCount}}</li>
          <li> 校验时间：{{repContent.repContent[0].date}}</li>
        </ol>
        <div>
          <div style="border: 1px solid #000 ; float:right">
            tips:
            <ol>
              <li>1.前置规则不满足公式 +主规则满足公式  有风险</li>
              <li>2. 前置规则不满足公式 +主规则不满足公式</li>
              <li>3. 前置规则  满足公式   被前置挡住</li>
            </ol>
                  </div>
          <span   class="setinput"> 查询： <el-input v-model="tablesearch" size="mini"></el-input><el-button @click="getRuleResult">查询指标结果</el-button></span>
          <br>
          <span>查询结果：result:{{ruleresult.result}}，reslutValue: {{ruleresult.reslutValue}},  paraValues: {{ruleresult.paraValues}} ,createDate: {{ruleresult.createDate}}</span>

          <el-table
            :data="repContent.repContent[0].ruleResults.filter(data => !tablesearch || data.ruleId.toString().includes(tablesearch.toLowerCase()))"
            style="width: 100%">

            <el-table-column
              label="规则名称"
              prop="ruleName" width="100px">
            </el-table-column>

            <el-table-column
              label="规则id"
              prop="ruleId"  width="120px">
            </el-table-column>

            <el-table-column
              label="申报表编号"
              prop="sbbBh"  width="100px">
            </el-table-column>

            <el-table-column
              label="申报表名称"
              prop="ruleName" width="200px">
            </el-table-column>

            <!--<el-table-column-->
              <!--label="错误信息"-->
              <!--prop="ruleTip"  width="250px">-->

              <!--<template slot-scope="scope">-->


                <!--<pre>{{ scope.row.resultValue ?'通过' : '不通过'}}</pre>-->

              <!--</template>-->

            <!--</el-table-column>-->



            <el-table-column
              label = "错误信息"

            >

              <template slot-scope="scope">


                <pre>{{ scope.row.ruleTip  }}</pre>

              </template>
            </el-table-column>
          </el-table>




        </div>



      </div>





    </div>

  </div>

</template>

<script>
  import {uploadzip , getZipList,getjufanFileContents,submitfiles,downloadzip,sendzip,getsqlenvs,getRuleInfo,getRedisFiles,updataRedisContent,savezChanges,getRuleResult}  from '../../api/shuiyoustools'
  import Xml2js from 'xml2js'
  import $ from 'jquery'
  import  vue from 'vue'
  import jsonpath from 'advanced-json-path'
  import {dataTranferToCascade,arrObjectDistinct} from '../../util/dataTranfer'
  import ruleInfo from './components/ruleInfo'
  import selectTool from './components/selectTool'
  import filevalueChangeComponent from './components/filevalueChangeComponent'
  export default {
    name: "szjkzip",
    components:{
      ruleInfo,
      selectTool,
      filevalueChangeComponent
    },
    data(){
      return {
        downloadURL: '',

        cwtype:[

          {
            name:'担保业',
            dm:'ZL1001039'
          },

          {
          name:'一般企业会计准则',
          dm:'ZL1001001'
        },{
            name:'政府会计制度_单位',
            dm:'ZL1001051'
          }, {
          name:'银行业',
          dm:'ZL1001036'
        },{
          name:'保险业',
          dm:'ZL1001038'
        },{
          name:'证券业',
          dm:'ZL1001037'
        },{
          name:'金融已执行',
          dm:'ZL1001050'
        },{
          name:'其他会计制度',
          dm:'ZL1001023'
        },{
          name:'小企业会计准则',
          dm:'ZL1001003'
        },{
          name:'企业会计制度',
          dm:'ZL1001002'
        },],

        loginuserflag:false,
        jufaanguserid:"",
        tempjufanloginuser:'',

        uploadURL:'',
        uploadData:{user:"dfdfdfd"},
        filenames:[],
       // zipselect:'',
        zipselectdto:{},
        sqlevns:[],
        ruleId:'',
        envid:1, // JUFAN("局端",1),YUNDUAN("云端",2);


        zipselectcascade:[],

        selectziptype : '',
        zipZLBSXL : '',

        casetitle:'',
        tablesearch : '',
        zipdtos : [],
        zipdtoCascade:[],

      //  redisFiles:[],  //  redis中的两个文件  格式为json
        zipfiles : [],  // 这里包括zip中的文件 和redis中的文件
        ruleinfo :[],

        saveFlag : true,
        submitFlag : true,

        repContent : '',

        zipfileurl:'', // 用于修改完文件后 将修改后的zip下载下来（仅临时使用，防止发送zip接口来不及完成的情况）

        fileString:"121212",
        xmlObject: {},
        filename:'',
        subxmlObject:{},
        tasks:[],
        express:'',
        keys:[],
        iscwbw:false,
        cjbdxmlExpression:'$.service.body',//写死
        cjbdxmlExpressionNoJsonPath : 'service.body',

        loading: false,
        changeRecord:{
          zipname:'',
          filechange:[  {
            filename: '',
            change:[]
          }],
          repContent:''
        },


        calculateExpression :'',
        calcaulateValue : '',
        senddisabled:false,
        ruleresult:'',

      };
    },
    methods:{

      getzipZLBSXLindex(index){
        console.log('===selectziptype===')
        console.log(index)
        this.zipZLBSXL = this.cwtype[index].dm
      },

      changeLoginflage(flag){
        this.loginuserflag = flag
      },

      login(){
        localStorage.setItem("currentjufanuserid",this.tempjufanloginuser)
        this.jufaanguserid = this.tempjufanloginuser.trim()
        this.loginuserflag = !this.loginuserflag
       // this.$store.dispatch('setloginflag',false)
        // this.loginflag = false
      },
      getjufanguserid(){
        this.jufaanguserid = localStorage.getItem("currentjufanuserid")
      },

      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      beforeRemove(file, fileList) {
        // return this.$confirm(`确定移除 ${ file.name }？`);
      },
      submit(e){
        console.log(e)

        this.$notify({
          title: '提示',
          message: '这是一条不会自动关闭的消息',
          duration: 0
        });


      },
      /**
       * 获取上传文件子文件名
       */
      onsuccess(rep){
        this.$notify({
          title: '提示',
          message: rep,

        });
      },

      getziplist(){
        let that = this
        console.log("=====")
        getZipList()
          .then(res => {
            console.log(res)
            this.zipdtos = res.data

            this.zipdtoCascade = dataTranferToCascade(res.data,'type','type')
            console.log(this.zipdtoCascade)
          }).catch(err => {
            that.warn("获取zip包失败，请刷新页面")
         // this.$alert(err.data, 'error')
        })
      },



      getFilesContent(value){
        let zipdtofilters =this.zipdtos.filter(t=>{
          console.log(t.id)
          console.log(value[value.length-1])
          if (t.id == value[value.length-1]){
            console.log("==here==")
            return t;
          }
          // console.log(zipdto)
        })
        let zipdto = zipdtofilters[0]
        this.zipselectdto = zipdto

        this.selectziptype = zipdto.type
        //console.log(index)
        getjufanFileContents(zipdto)
          .then(rep=>{
            this.zipfiles = rep.data



          }).catch(err => {
          this.$alert(err.data, 'error')
          return;
        })

        this.submitFlag = false
        // this.repContent = '';
        this.changeRecord =
          {


            zipname:'',
            filechange:[],
            repContent:''


          };

        this.changeRecord.zipname =zipdto.name

      },

      /**
       * 将 content 内容转为 json,并存储到xmlobject 中,
       * @param value
       */
      getFileObject(index){

        console.log('change'+ index)

        this.readXml(this.zipfiles[index])

        this.saveFlag = false

      },


      getUploadUrl(){
        console.log("getuploadurl")
        //this.downloadURL = downloadzip()
        this.uploadURL = uploadzip()
        //return 'https://jsonplaceholder.typicode.com/posts/'
      },

      executorListchange(){
        this.readXml()
        this.tasks = []


      },
      /**
       * 将 xml 格式 转为 json  并赋给xmlobject 或subxmlobject
       *
      * */
      async readXml(value,iscwbw){    //  将 xml 格式 转为 json  并赋给xmlobject 或subxmlobject
        
        let that = this
        that.xmlObject = {}
        that.subxmlObject = {}

        if (value.name == 'redis_cwbb' || value.name == 'redis_base'){
            that.xmlObject = JSON.parse(value.content)
          return
        }
        let xmlParser = new Xml2js.Parser({explicitArray: false, ignoreAttrs: false});



         var promise = new Promise(((resolve, reject) => {



          xmlParser.parseString(value.content,function (err,rep) {
            if (null!= err){console.log(err);return}
            resolve(rep)
            console.log('value.content')
            //console.log(rep)
          })

        }))
        await promise.then( async value =>{
          console.log(value)
          that.xmlObject = value
            console.log('vue.promise')

          let needXmlbw =''
          if(iscwbw){
            needXmlbw = jsonpath(that.xmlObject,that.cjbdxmlExpression)

            let xmlParser = new Xml2js.Parser({explicitArray: false, ignoreAttrs: false});
            console.log('needxmlbw')
             console.log(needXmlbw)
            if (needXmlbw.indexOf('<![CDATA')!= -1){
              let rescdata = /<!\[CDATA\[(.*)\]\]>/
            //  console.log(rescdata.exec(strcdta))
                needXmlbw = rescdata.exec(needXmlbw)[1]
            }
         await   xmlParser.parseString(needXmlbw,function (err,repsub) {
              if (null != err) {
                that.warn('请确认报文类型，再重新上传文件')
                // warn()
                console.log(err);
                return
              }
              console.log('read subxmlob')
              console.log(repsub)

              that.subxmlObject = repsub;
              console.log(JSON.stringify(that.subxmlObject))

              console.log('readsubxml over')
             // resolve(rep)
            })


          }
          console.log('readxml over')
          //this.fileString = this.xmlObject.taxML.ywbw.A100000.zbForm.yysr

          //  console.log(jsonpath(value,'$.taxML.ywbw.A100000.zbForm.yysr'))

        })

      },

      /**
       * 读取tasks ,
       */
     async savexml(){


        // let newtask={
        //   xmlIndex:-1,
        //   iscwbw:false,
        //   key:'',
        //   value:'',
        //   editable:true
        // }

        console.log('savexml')
        console.log(this.tasks)
        let that = this;
        this.changeRecord =
          {


            zipname:'',
            filechange:[],
            repContent:''


          };


        for(let i in this.tasks){
          let row = this.tasks[i]
          //1.readxml 转化赋值 subxmloject 及 xmlobect

            // that.readXml()

          /**
          *  需要额外处理redis 和 oracle
          *
          * */


       await     that.readXml(that.zipfiles[row.xmlIndex],row.iscwbw)
            // 将修改后的task值 注入

           //that.setValue(row.key,)

        await  that.setValue(row.key, row.iscwbw ?that.subxmlObject : that.xmlObject,row.value)

            if (JSON.stringify(that.xmlObject) == '{}') return;
            let xml = ''
            if (that.zipfiles[row.xmlIndex].name == 'redis_cwbb' || that.zipfiles[row.xmlIndex].name == 'redis_base'){//value.name == 'redis_cwbb' || value.name == 'redis_base'
              // if (that.zipfiles[row.xmlIndex].name == 'redis_base') {
              //   that.setValue('SB_ZLBSCJB_ETL.ZLBSXL_DM',that.xmlObject,that.zipZLBSXL)
              // }
                xml = JSON.stringify(that.xmlObject)
            }else{
              that.setValue('taxml.djxh',row.iscwbw ?that.subxmlObject : that.xmlObject,that.jufaanguserid)
              let xmlBuild = new Xml2js.Builder();
              let subxml;
              if (row.iscwbw){
                subxml =  xmlBuild.buildObject(that.subxmlObject)
               // await that.setValue()
               await that.setValue(that.cjbdxmlExpressionNoJsonPath,that.xmlObject,subxml)
              }

              xml = await xmlBuild.buildObject(that.xmlObject);
            }




            let xmlchange = {filename:'',change:[]}
            xmlchange.filename = that.zipfiles[row.xmlIndex].name
            xmlchange.change =(JSON.parse(JSON.stringify(row)))
            that.changeRecord.filechange.push(xmlchange)

            that.zipfiles[row.xmlIndex].content = xml

          }
      },
      async submitChange(){
       if (this.ruleId.trim() == '' || this.jufaanguserid == '' || this.casetitle.trim() == '' || this.zipZLBSXL == '') {  //判断 ruleid 。nsrid是否为空
         this.warn("规则id 或 用户id为空 或 标题为空")
         return
       }
       
       
        if (!this.saveFlag  ){

          this.$alert('请先保存xml修改', '标题名称', {
            confirmButtonText: '确定',
            callback: action => {
              this.$message({
                type: 'info',
                message: '请先保存xml修改'
              });
            }
          });
          return;

        }
        if ( this.zipfiles.length == 0 ){

          this.$alert('请重新选择zip文件', '标题名称', {
            confirmButtonText: '确定',
            callback: action => {
              this.$message({
                type: 'info',
                message: '请重新选择zip文件'
              });
            }
          });
          return;

        }

        let redisfiles = {redis_cwbb:'',redis_base:''}
        let zipfiledtos = []
        for(let i in this.zipfiles) {
          if (this.zipfiles[i].name == 'redis_cwbb'  ) { //value.name == 'redis_cwbb' || value.name == 'redis_base'

            redisfiles.redis_cwbb = this.zipfiles[i].content


          } else if(this.zipfiles[i].name == 'redis_base'){
            redisfiles.redis_base = this.zipfiles[i].content
          }else {
            //需要处理名字
            this.zipfiles[i].name = this.zipfiles[i].name.replace('304',this.jufaanguserid)
            zipfiledtos.push(this.zipfiles[i])
          }
        }
    await updataRedisContent(this.jufaanguserid,redisfiles).then(res => {
        console.log('updataRedisContent')
    }).catch(err=>{
      this.$alert(err.data, JSON.stringify(err.data))
      return;
    })


     await   submitfiles(this.zipselectdto.id,this.casetitle,zipfiledtos)
          .then(rep=>{
            this.zipfileurl = rep.data
            console.log(this.zipfileurl)
          }).catch(err=>{
          this.$alert(err.data, 'error')
          return;
        })
      this.saveChanges()

        /**
        *
        * 提交后重置zipfiles
        *
        * */
      await  getjufanFileContents(this.zipselectdto)
          .then(rep=>{
            this.zipfiles = rep.data



          }).catch(err => {
          this.$alert(err.data, 'error')
          return;
        })







      },
       async send(){
         if (this.ruleId.trim() == '' || this.jufaanguserid == '' || this.casetitle.trim() == '' || this.zipZLBSXL == '' || this.zipfiles.length == 0) {  //判断 ruleid 。nsrid是否为空
           this.warn("有内容未填 ")
           return
         }

         // let changeExpressiondto = {
         //   id:0,
         //   zipFileId:0,
         //   fileName:'redis_base',
         //   expression:'SB_ZLBSCJB_ETL.ZLBSXL_DM',
         //   changeValue:this.zipZLBSXL,
         //   type:1,
         // }
         // let changeExpressiondtodjxh = {
         //   id:0,
         //   zipFileId:djxhfileid,
         //   fileName:'',
         //   expression:'taxml.djxh',
         //   changeValue:this.jufaanguserid,
         //   type:3,
         // }
         //
         // changearr.push(changeExpressiondtodjxh)
         // changearr.push(changeExpressiondto)
         let changezipzlbsxlindex = ''
         let changeExpressiondtodjxhindex= ''

         for (let i in this.zipfiles) {
            if (this.zipfiles[i].name == 'redis_base'){
              changezipzlbsxlindex=i
            }
            if (this.zipfiles[i].id != 0) {
              changeExpressiondtodjxhindex = i
            }
         }


         //需要阄要改的值 加到到tasks里
         let changezipzlbsxl={
           xmlIndex:changezipzlbsxlindex,
           iscwbw:false,
           key:'SB_ZLBSCJB_ETL.ZLBSXL_DM',
           value:this.zipZLBSXL,
           editable:false
       }
      let changeExpressiondtodjxh = {
        xmlIndex:changeExpressiondtodjxhindex,
        iscwbw:true,
        key:'taxml.djxh',
        value:this.jufaanguserid,
        editable:false
      }

        this.tasks.push(changezipzlbsxl)
        this.tasks.push(changeExpressiondtodjxh)


       this.senddisabled = true
         this.loading = true
       await  this.savexml()
        await  this.submitChange()
        let tempptask = []
         tempptask = this.deleteArrObj(this.tasks,'key','SB_ZLBSCJB_ETL.ZLBSXL_DM')
         tempptask = this.deleteArrObj(tempptask,'key','taxml.djxh')
      this.tasks = tempptask

       // if (this.this.zipfileurl.path == '')
        let params = {
          typeid : this.selectziptype,
          path : this.zipfileurl.path
        }
        sendzip( params)
          .then(rep=>{
            console.log(JSON.stringify(rep.data).replace(/\\/g,""))

            // JSON.parse(JSON.stringify(rep.data).replace(/\\/g,""))



            this.changeRecord.repContent = JSON.parse(rep.data)
            // this.repContent =  JSON.stringify(this.changeRecord).replace(/\\/g,"")
            this.repContent = this.changeRecord
            this.loading =false
            this.senddisabled=false
          }).catch(err=>{
            this.loading = false
            this.warn('sendzip error')
        })




      },
      verifyRep(){

      },


      resetall(){
        this.tasks = []
        this.zipfiles = []
        this.saveFlag = true
        this.submitFlag = true
        this.subxmlObject = {}
        this.xmlObject = {}
        this.zipselectdto = {}
        this.changeRecord = ''
        this.repContent = ''

      },
      getziffileIndex(value){

        for (let index in this.zipfiles){
          console.log(index)
          if (this.zipfiles[index].id = value.id) {
            return index;
          }
        }


      },




      downLoadFile(){
        /*      if (JSON.stringify(this.xmlObject) == '{}') return;
              let xmlBuild = new Xml2js.Builder();
              let subxml;
              if (this.iscwbw){
                subxml =  xmlBuild.buildObject(this.subxmlObject)
                this.setValue(this.cjbdxmlExpressionNoJsonPath,this.xmlObject,subxml)
              }

              let xml = xmlBuild.buildObject(this.xmlObject);
              console.log(xml)

              console.log("downloadfile")
              let content = xml
              let fileName= this.filename
              let aTag = document.createElement('a');
              let blob = new Blob([content]);　　// 这个content是下载的文件内容，自己修改
              aTag.download = fileName;　　　　　　// 下载的文件名
              aTag.href = URL.createObjectURL(blob)

              aTag.click();
              URL.revokeObjectURL(blob)*/


        let param = {
          fileName : this.zipfileurl.path
        }
        downloadzip(param)
          .then(rep=>{
            console.log(rep)
            let fileName= "121212.zip"
            let aTag = document.createElement('a');
            let blob = new Blob([rep.data]);　　// 这个content是下载的文件内容，自己修改
            aTag.download = this.zipfileurl.filename;　　　　　　// 下载的文件名
            aTag.href = URL.createObjectURL(blob)

            aTag.click();
            URL.revokeObjectURL(blob)
          })


      },

      calculate(){
        console.log(this.calculateExpression )
        this.calcaulateValue =eval(this.calculateExpression )
        console.log(this.calcaulateValue)
        return eval(this.calculateExpression )
      },

/**
 * 删除arr中满足条件的objc
 *
 * */
      deleteArrObj(arr,objkey,objkeyvalue){
    let arrtemp = []
    for (let i in arr){
      console.log(arr[i][objkey] == objkeyvalue)
      if (arr[i][objkey] != objkeyvalue){
        arrtemp.push(arr[i])
      }
    }
    return arrtemp
  },



      addNewTask(tasks){
        let newtask={
          xmlIndex:-1,
          iscwbw:false,
          key:'',
          value:'',
          editable:true
        }
        tasks.push(newtask)
      },

      edit(value2, index) {
        console.log(index)
        vue.set(value2, 'editable', true)
      },
      setRowXmlIndex(event,row){
        console.log("-----event--")
        console.log(event)
        console.log('----row-----')
        console.log(row)
        vue.set(row,'xmlIndex',event)

        console.log('$refs')
        console.log(this.$refs)

      },
      setRowIscwbw(event,row){
        vue.set(row,'iscwbw',event)
        console.log('clickiscwbw')
        console.log(row)
      },

      deletetask(index,row){

        this.tasks.splice(index,1)
        // return

        // vue.delete(row,'editable')

      },
     async   updatetask(row) {
        // if(row.name != '' && row.name )

        // this.row.key =  this.keyCalibration(row.key.trim(),this.xmlObject)
        let that = this;
        //1、请先选择 xml表
        if(row.xmlIndex == -1){
          this.warn("请先选择xml")
          return
        }
     await   this.readXml(this.zipfiles[row.xmlIndex],row.iscwbw)
       // this.sleep(5000)

       console.log(this.xmlObject)
       console.log("begin sleep")
       // vue.set(row,'key',that.keyCalibration(row.key.trim(),row.iscwbw ?that.subxmlObject : that.xmlObject)) //先校准key
        vue.delete(row, 'editable')

        vue.set(row,'value',that.findValue(row.key.trim(),row.iscwbw ?that.subxmlObject : that.xmlObject))



      },

      updateValue(row,index){
        vue.delete(row,'editable')
      },

      /**
       * 需要处理多种表达式
       * */
      findValue (expre,obj) {
        console.log("findvalue")

       let expressionobj =  this.expressionManage(expre,obj)
        console.log(expressionobj)
        let expression = expressionobj.exp
        console.log(expression)
        let arr = expression.replace(/\"/g,'').split(',')
        let j =obj
        if (expressionobj.type == 2){
          return '删除节点'
        }

        if (expressionobj.type == 1){
          if (arr.length  == 4){// 'xml.key.value,"aa","a","bb'


            let searchkey = arr[1].trim()
            let searchValue = arr[2].trim()
            let changekey = arr[3].trim()
            let subarr = arr[0].split('.');
            let isFindSearchValue = false;
            for (let i in subarr){
              j=j[subarr[i]]
            }
            console.log(JSON.stringify(j) )


            for (let i in j){
              if (j[i][searchkey] == null){
                continue
              }
              console.log(j[i][searchkey] == null)
              console.log(j[i])
              console.log('actual value:'+j[i][searchkey])
              console.log('searvalue:'+searchValue)
              console.log(j[i][searchkey] == searchValue)
              if (j[i][searchkey] == searchValue){

                j= j[i][changekey]
                isFindSearchValue = true
                break
              }
            }

            if (!isFindSearchValue){
              this.warn(`未发现值为${searchValue}的键${searchkey}`)
              return
            }

          } else {    // xml.key.value2

            let subarr =   expression.split('.')

            for (let i in subarr){

              j=j[subarr[i]]
            }


          }
          return j
        }

        if (expressionobj.type == 3){
          if (arr.length == 2){ // sum  返回所有此key的值 ，以 , 相隔
            let res = []
            console.log("sum类型")
            let subarr = arr[0].split('.')
            let searchkey = arr[1]
            for (let i=0;i<subarr.length ; i++){
              j = j[subarr[i]]
            }

            for (let i in j){
              res.push(j[i][searchkey])
            }


            return '个数：'+j.length +':值'+ JSON.stringify(res)

          }
          if (arr.length == 4){
            let res = []
            console.log("sum类型")
            let subarr = arr[0].split('.')
            let searchkey = arr[1]
            let searchValue = arr[2]
            let changekey = arr[3]
            for (let i=0;i<subarr.length ; i++){
              j = j[subarr[i]]
            }
            for(let i in j){
              if (j[i][searchkey] == searchValue){

                res.push(j[i][searchkey])
              }
             // res.push()
            }
            return '个数：'+j.length +':值'+ JSON.stringify(res)
          }

        }

        if (expressionobj.type == 4) {
          let res = []
          let subarr = arr[0].split('.')
          for (let i=0;i<subarr.length ; i++){
            j = j[subarr[i]]
          }

          for(let i =2;i<arr.length;i++){
              res.push(j[arr[i]])
          }
          return '个数：'+j.length +':值'+ JSON.stringify(res)
        }






        return j
      },

      /**
       * expression表达示过滤处理
       * 对expression进行格式化
       * DSF.isNotSubstring(bblxmc,SDS.getQylxFor2019(a000000.qyjcxxb2018Form.qysdsnbcjcwkjzdflDm)
      -- DSF.isNotSubstring(bblxmc,'2000')
      -- DSF.isEqual(DSF.nvl(bblxdm,"A"),"A")
      -- DSF.isNotExist(xqylrbnb)
       SDS.getQylxFor2019(a000000.qyjcxxb2018Form.qysdsnbcjcwkjzdflDm)
      -- CF.sumProp(a000000.qyzygdjfhqkGrid.qyzygdjfhqkGridlbVo,"tzbl")
       DSF.nvl({基础信息表A000000_其余股东合计投资比例},0)
       *
       *
       * type 1 更改一个value值   type 2 删除key
       * */
      expressionManage(expres,obj){
        console.log('expressionManage')
        let that = this
        let expression = expres.replace(' ','')
        let ob = { exp:'', type :'' }  // type 1 更改value值   type 2 删除key  t type 3 集合  type 4 ifprop 判断满足条件的属性值个数
        if (expression.trim().indexOf('DSF.isNotExist') != -1){
          let exp = this.getIsNotExistRegexp(expression.trim(),/DSF.isNotExist\((.*)\)/)
          exp = this.keyCalibration(exp, obj,2)
          return { exp: exp , type:2}
        }

        if (expression.trim().indexOf('SDS.getValue') != -1){
          let exp = this.getIsNotExistRegexp(expression.trim(),/SDS.getValue\((.*)\)/)
          console.log()
          console.log(exp)
          exp = this.keyCalibration(exp,obj,1)

          return {exp:exp,type:1};
        }

        if (expression.trim().indexOf('DSF.isNotSubstring') != -1) {
         // console.log('DSF.isNotSubstring')
          let exp = this.getIsNotExistRegexp(expression.trim(),/DSF.isNotSubstring\((.*),/)
          exp = this.keyCalibration(exp,obj,1)
         return {exp:exp,type:1}

        }

        if (expression.trim().indexOf('CF.sumProp(') != -1){   ///CF.sumProp\((.*)\)/
          let exp = this.getIsNotExistRegexp(expression.trim(),/CF.sumProp\((.*)\)/)
          exp = this.keyCalibration(exp,obj,3)
          return {exp:exp,type:3}
        }
        if(expression.trim().indexOf('DSF.isEqual') !=-1){  // /DSF.isEqual\((.*)\)/
          let exp = this.getIsNotExistRegexp(expression.trim(),/DSF.isEqual\((.*),/)
          exp = this.keyCalibration(exp,obj,3)
          return {exp:exp,type:1}
        }

        if(expression.trim().indexOf('DSF.nvl')!=-1){  // /DSF.isEqual\((.*)\)/
          let exp = this.getIsNotExistRegexp(expression.trim(),/DSF.nvl\((.*),/)
          exp = this.keyCalibration(exp,obj,1)
          return {exp:exp,type:1}
        }
        if(expression.trim().indexOf('SDS.getQylxFor2019')!=-1){  // /DSF.isEqual\((.*)\)/
          let exp = this.getIsNotExistRegexp(expression.trim(),/SDS.getQylxFor2019\((.*)\)/)
          exp = this.keyCalibration(exp,obj,1)
          return {exp:exp,type:1}
        }
        //======================
        if(expression.trim().indexOf('SDS.getCollectionByCodeStr')!=-1){  // /DSF.isEqual\((.*)\)/
          let exp = this.getIsNotExistRegexp(expression.trim(),/SDS.getCollectionByCodeStr\((.*)\)/)
          exp = this.keyCalibration(exp,obj,3)
          return {exp:exp,type:3}
        }
        if(expression.trim().indexOf('SDS.valueByCondFromMap')!=-1){  // /DSF.isEqual\((.*)\)/
          let exp = this.getIsNotExistRegexp(expression.trim(),/SDS.valueByCondFromMap\((.*)\)/)
          let arr = exp.split(',')
           exp = arr[0]+','+arr[2]+','+arr[3]+','+arr[1]
          exp = this.keyCalibration(exp,obj,1)
          return {exp:exp,type:1}
        }
        if(expression.trim().indexOf('SDS.ifPropValueGtZeroNum')!=-1){  // /DSF.isEqual\((.*)\)/
          let exp = this.getIsNotExistRegexp(expression.trim(),/SDS.ifPropValueGtZeroNum\((.*)\)/)
          exp = this.keyCalibration(exp,obj,4)
          return {exp:exp,type:4}
        }
        if(expression.trim().indexOf('CF.sumPropWithCond')!=-1){  // /DSF.isEqual\((.*)\)/
          let exp = this.getIsNotExistRegexp(expression.trim(),/CF.sumPropWithCond\((.*)\)/)
          exp = this.keyCalibration(exp,obj,3)
          console.log(exp)
          return {exp:exp,type:3}
        }
        if(expression.trim().indexOf('SDS.notExistsBySbq')!=-1){  // /DSF.isEqual\((.*)\)/
          let exp = this.getIsNotExistRegexp(expression.trim(),/SDS.notExistsBySbq\((.*)\)/)
          exp = this.keyCalibration(exp,obj,3)
          return {exp:exp,type:3}
        }

        // ======================

        if (expression.indexOf('(') == -1){
          return { exp:this.keyCalibration(expression,obj) , type:1 }
        }

        this.warn("不能识别表达式："+expres + ',请通知何森存')
        return null;


      },

      /**
       *
       * 需要处理expression
       * */
      setValue(expre,obj,updatevalue) {

        if(typeof (updatevalue) != "number"){
          updatevalue = updatevalue.trim()
        }

       let expressionobj =  this.expressionManage(expre,obj)
        let expression = expressionobj.exp
        console.log('begin setvalue')
        console.log('输出完成')
        //DSF.isNotExist
         let isnotexistFlag = false
        let arr = expression.replace(/\"/g,'').split(',')
        let j =obj
          if (expressionobj.type == 2){
            console.log('删除节点')
            console.log(expression)
            isnotexistFlag = true
            expression = expressionobj.exp
            console.log(expression)
            let j =obj

            let subarr =   expression.split('.')
            for (let i in subarr){
              console.log(j)
              console.log(subarr[i])
              if (i == subarr.length -1   ){
                console.log('delete')
                //console.log(j)
                delete j[subarr[i]]
                //console.log(j)
                break
              }
              if (j[subarr[i]] != null){
                j = j[subarr[i]]
              }
            }
            return

          }

          if (expressionobj.type ==1){
            console.log('expressionobj,type=1')
            if (arr.length == 4){// 'xml.key.value,"aa","a","bb'
              console.log(arr)
              console.log(updatevalue)
              let subarr = arr[0].split('.')

              for (let i in subarr){
                j=j[subarr[i]]
              }

              for (let i in j){
                let key = arr[1]
                let searchValue = arr[2].trim()
                let changekey = arr[3].trim()
                console.log('j[i][key] == searchValue')
                console.log(j[i][key])
                console.log(j[i][key] == searchValue)
                if (j[i][key] == searchValue){
                 let value =  this.typeExchange(j[i][key],updatevalue)
                  j[i][changekey] = value
                  return
                }
              }

            } else {    // xml.key.value2

              let subarr =   expression.split('.')

              for (let i in subarr){
                console.log(updatevalue)
                console.log(i)
                if (i== subarr.length-1){
                  let value =  this.typeExchange(j[subarr[i]],updatevalue)
                  console.log('============')
                  j[subarr[i]]=value
                  return
                }
                j=j[subarr[i]]
              }

            }
          }

          if (expressionobj.type == 3){
            if (arr.length ==2 ) {//sum 改变里面所有的值
              let res = []
              console.log("sum类型")
              let subarr = arr[0].split('.')
              let searchkey = arr[1]
              for (let i=0;i<subarr.length ; i++){
                j = j[subarr[i]]
              }

              for (let i in j){
                let value =  this.typeExchange(j[i][searchkey],updatevalue)
                j[i][searchkey] = value
              }


              return ;
            }

            if (arr.length == 4){              // 'xml.key.value,"aa","a","bb'
              let subarr = arr[0].split('.')

              for (let i in subarr){
                j=j[subarr[i]]
              }

              for (let i in j){
                let key = arr[1]
                let searchValue = arr[2]
                let changekey = arr[3]

                if (j[i][key] == searchValue){
                  let value =  this.typeExchange(j[i][changekey],updatevalue)
                  j[i][changekey] = value

                }
              }

            }


          }

          if(expressionobj.type == 4){
            let subarr = arr[0].split('.')

            for (let i in subarr){
              j=j[subarr[i]]
            }
            for (let i =2 ;i<arr.length;i++){
              let value =  this.typeExchange(j[arr[i]],updatevalue)
              j[arr[i]] = value
            }
          }








        console.log(obj)
        console.log('set value 结束')

      },
      /**
       * 判断基准值  和  输入值 ，将输入的值的数据类型 转换为基准值的数据类型  ，
       * */
      typeExchange(base , input){
        if (typeof (base) == "number") {

          return  Number(input)
        }

        if(typeof (base) == "string"){
          return input.trim()
        }

        return input.trim()
        this.warn("typeExchange,类型错误")


      },



      /**
       * 校准key，不能有外包 xxx.exist等
       * @param expression
       * @param obj
       * @returns {string}
       */
      keyCalibration  (expression,obj,type) {  //根据  json中大小写 来校准  expression 中的key值 ,type 专用于SDS.ifPropValueGtZeroNum

        let startStr = 'taxML'


        console.log('keyCalibration contains')

        console.log(expression)
        console.log(obj)

        if ( this.getObjkey(obj)[0].toLowerCase() == startStr.toLowerCase()){  //查看obj的第一个元素是否为taxml  否刚不加taxml
          if (!expression.toLowerCase().startsWith(startStr.toLowerCase())) {
            expression = 'taxML.'+expression
            console.log('expression:'+expression)
          }
        }
        // console.log(!expression.toLowerCase().startsWith(startStr.toLowerCase()))





        let arr = expression.replace(/\"/g,'').split(',')
        let subarr = arr[0].split('.')

        let objtmp = obj
        let isFindKey = true

        for (let i in subarr){   //校准subarr
          if (!isFindKey && i>0){
            //执行 没有发现key  未发现
            this.warn('找不到对应键值：'+subarr[i-1])
            return
          }
          let keys = this.getObjkey(objtmp)
          for(let j in keys){
            isFindKey = false

            if (keys[j].toLowerCase() == subarr[i].toLowerCase()){
              subarr[i]=keys[j]
              objtmp = objtmp[keys[j]]
              isFindKey = true
              break
            }


          }


        }
        if (!isFindKey ){
          //执行 没有发现key  未发现
          this.warn('找不到对应键值：'+arr[0])
          return
        }

        if(type == 4){  //不是arr ，是obj
          for (let key in objtmp){
            for (let i =2 ;i<arr.length;i++){
              if (arr[i].toLowerCase().trim() == key.toLowerCase()){
                arr[i] = key
                break
              }
            }
          }
        }
        if (arr.length ==2 && type != 4){

          let flagsum = 0

          for( let index in objtmp){
            let keys = this.getObjkey(objtmp[index])
            console.log('输出扫描的二维key')
            for (let j in keys){
              console.log(keys[j])
              if (keys[j].toLowerCase().trim() == arr[1].toLowerCase().trim()){
                arr[1] = keys[j]
                flagsum++
                break;
              }
            }
            if (flagsum >0){
              break
            }

          }

          if (flagsum == 0){
            this.warn('找不到对应键值：'+arr[1] )
          }

        }



        if (arr.length == 4 && type != 4){
          //校准 二维数据
          let flag =0


          for( let index in objtmp){
            let keys = this.getObjkey(objtmp[index])
            console.log('输出扫描的二维key')
            for (let j in keys){
              console.log(keys[j])
              if (keys[j].toLowerCase().trim() == arr[1].toLowerCase().trim()){
                arr[1] = keys[j]
                flag++

              }
              if (keys[j].toLowerCase().trim() == arr[3].toLowerCase().trim()){
                arr[3] = keys[j]
                flag++
              }

              if (flag == 2 ){
                break
              }

            }
            if (flag == 2){
              break
            }

          }




          if (flag <2 ){
            //执行 没有发现key  未发现
            this.warn('找不到对应键值：'+arr[1] +'或' + arr[3])

            return
          }
        }



        //重新组装
        let newEXpre = ''
        for (let index in subarr){
          if (subarr.length -1 == index) {
            newEXpre = newEXpre + subarr[index]
          }else{
            newEXpre = newEXpre + subarr[index]+'.'
          }


        }
        for(let i =1 ; i<arr.length ;i++){
          newEXpre = newEXpre +','+ arr[i]
        }

      console.log('校准完成')
    console.log(newEXpre)
        return newEXpre

      },
      sleep(delay) {
        let start = (new Date()).getTime();
        while ((new Date()).getTime() - start < delay) {
          continue;
        }
        console.log('sleep over')
      },

      getObjkey (obj) {
        let arr=[]
        for (let i in obj){
          arr.push(i)
        }

        return arr
      },


      warn(message) {
        this.$alert(message, '标题名称', {
          confirmButtonText: '确定',
          callback: action => {
            this.$message({
              type: 'info',
              message: `action: ${ action }`
            });
          }
        });
      },


      getIsNotExistRegexp(expression,reg){
      console.log(expression)
        console.log(reg)



       return  reg.exec(expression)[1]

       // console.log(reg.exec(expre)[1])


      },
      getRuleInfo(){
       if (this.ruleId.trim() == ''){
         this.warn("请输入规则id")
         return
       }
        getRuleInfo(this.envid,this.ruleId).then(rep=>{
          this.ruleinfo = rep.data
          //根据结果初始化tasks的值
          console.log('inittasks')

          this.inittasks(rep.data.ruleVarDtos)
       // console.log()
         // console.log(this.$refs)

        //this.clearSelect()

        }).catch(err=>{
          console.log('err:getRuleInfo')
          console.log(err.data)
          this.$alert(err.data, 'err:getRuleInfo')
          return;})
      },

      inittasks(rulevo){//初始化tasks
        this.tasks = []
       let distinctarr =  arrObjectDistinct(rulevo,'varValue')
        for (let i in distinctarr){
          let newtask={
            xmlIndex:-1,
            iscwbw:false,
            key:'',
            value:'',
            editable:true
          }
          newtask.key = distinctarr[i].varValue
          this.tasks.push(newtask)

        }
        //清附select


      },
      clearSelect(){
        console.log('clearSelect')
       // console.log('refs')
        console.log(this.$refs.clearselect)
        for(let i in this.$refs.clearselect){
          this.$refs.clearselect[i].$emit('clearselect','adfd')
        }
      },

      /**
       *
       private long zipFileId;

       private String fileName;

       private String expression;

       //private String originValue;

       private String changeValue;

       private int type;    1. redis 2.oterdb  3. zipfile
       *
       * if (that.zipfiles[row.xmlIndex].name == 'redis_base') {
                that.setValue('SB_ZLBSCJB_ETL.ZLBSXL_DM',that.xmlObject,that.zipZLBSXL)
                 let newtask={
          xmlIndex:-1,
          iscwbw:false,
          key:'',
          value:'',
          editable:true
        }
       * */

      saveChanges(){
        let changearr = []
        let  djxhfileid = 0;
        for(let i in this.tasks){
          let zifiledto = this.zipfiles[this.tasks[i].xmlIndex]
          let type = (zifiledto.name == 'redis_base' || zifiledto.name == 'redis_cwbb')?1:3
          if (zifiledto.name != 'redis_base' && zifiledto.name != 'redis_cwbb') {
            djxhfileid = zifiledto.id
          }
          let changeExpressiondto = {
            id:0,
            zipFileId:zifiledto.id,
            fileName:zifiledto.name,
            expression:this.tasks[i].key,
            changeValue:this.tasks[i].value,
            type:type,
          }
          changearr.push(changeExpressiondto)
        }


        // let changeExpressiondto = {
        //   id:0,
        //   zipFileId:0,
        //   fileName:'redis_base',
        //   expression:'SB_ZLBSCJB_ETL.ZLBSXL_DM',
        //   changeValue:this.zipZLBSXL,
        //   type:1,
        // }
        // let changeExpressiondtodjxh = {
        //   id:0,
        //   zipFileId:djxhfileid,
        //   fileName:'',
        //   expression:'taxml.djxh',
        //   changeValue:this.jufaanguserid,
        //   type:3,
        // }
        //
        // changearr.push(changeExpressiondtodjxh)
        // changearr.push(changeExpressiondto)
        let that = this
        console.log(changearr)
        savezChanges(this.zipselectdto.id,this.casetitle,changearr)
          .then(res =>{

          }).catch(err=>{
            console.log('method:savechanges:'+err)
          console.log(err)
            that.warn('method:saveChanges:'+JSON.stringify(err))
        })

        return changearr
      },
      flushsenddisabled(){
        this.senddisabled = false
        this.loading=false
      },





      getRedisFiles(){
       getRedisFiles('304').then(rep=>{
          this.redisFiles = rep.data
       }).catch(err=>{
         this.$alert(err.data,'errer')
         return;})
      },
      getsqlenvs(){
        getsqlenvs().then(rep=>{
          this.sqlevns = rep.data
        }).catch(err=>{
          this.$alert(err.data, 'errer')
          return;
        })
      },
      getRuleResult(){

        this.ruleresult = {
          result:'',
          reslutValue:-1,
          paraValues:'',
          createDate:''
        }


        getRuleResult(this.jufaanguserid,this.tablesearch.trim()).then(res =>{

          if (res.data.length>0){

            this.ruleresult = res.data[0]
            // 1 ''  前置不通过   0 非空  主规则满足公式  1 非空  主规则不满足
            if (this.ruleresult.reslutValue == 1 && this.ruleresult.paraValues == null) {
              this.ruleresult.result = '被前置挡住'
            }
            if (this.ruleresult.reslutValue == 0 ) {
              this.ruleresult.result = '有风险'
            }
            if (this.ruleresult.reslutValue == 1 && this.ruleresult.paraValues != null) {
              this.ruleresult.result = '无风险'
            }


          }
        }).catch(err=>{
          this.warn("getRuleResultErr:"+JSON.stringify(err.data))
        })
      }
    },
    mounted(){
      this.getjufanguserid(),
      this.getUploadUrl(),
        this.getziplist()
     // this.getRedisFiles()
      //  this.getsqlenvs()
    },
    computed:{

    }

  }
</script>

<style scoped>

  .selectwidth >>> .el-select {
    display: inline-block;
    position: relative;
    width:500px;
  }


  .setinput >>> .el-input {


    position: relative;

    font-size: 14px;

    display: inline-block;

    width: 50%;

  }

  .calculate {
    width: 500px;
    float: right;
  }

  pre{
    white-space:pre-wrap; /* css3.0 */
    white-space:-moz-pre-wrap; /* Firefox */

    white-space:-o-pre-wrap; /* Opera 7 */
    word-wrap:break-word; /* Internet Explorer 5.5+ */
  }


</style>
